package cn.gogpay.duoim.sdk.service.v3;

import cn.gogpay.duoim.sdk.model.IMRespResult;
import cn.gogpay.duoim.sdk.model.v3.auth.req.ForceLogoutReq;
import cn.gogpay.duoim.sdk.model.v3.auth.req.ParseTokenReq;
import cn.gogpay.duoim.sdk.model.v3.auth.req.UserTokenReq;
import cn.gogpay.duoim.sdk.model.v3.auth.resp.ParseTokenResp;
import cn.gogpay.duoim.sdk.model.v3.auth.resp.UserTokenResp;
import cn.gogpay.duoim.sdk.model.v3.base.IMCertificate;
import cn.gogpay.duoim.sdk.service.IMApiFactory;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import okhttp3.Request;

public class IMAuthV3Service {

    /**
     * 获取用户token
     *
     * @param token 凭据
     * @param req   请求
     * @return 响应
     */
    public IMRespResult<UserTokenResp> userToken(IMCertificate token, UserTokenReq req) {
        req.setSecret(IMApiFactory.buildSecret());
        String params = JSONUtil.toJsonStr(req);
        Request request = IMApiFactory.buildCertifiedRequest(token, params, "/auth/user_token");
        String data = IMApiFactory.callRequest(request);
        TypeReference<IMRespResult<UserTokenResp>> typeReference = new TypeReference<IMRespResult<UserTokenResp>>() {
        };
        return JSONUtil.toBean(data, typeReference, false);
    }

    /**
     * 解析token
     *
     * @param token 凭据
     * @param req   请求
     * @return 响应
     */
    public IMRespResult<ParseTokenResp> parseToken(IMCertificate token, ParseTokenReq req) {
        String param = JSONUtil.toJsonStr(req);
        Request request = IMApiFactory.buildCertifiedRequest(token, param, "/auth/parse_token");
        String data = IMApiFactory.callRequest(request);
        TypeReference<IMRespResult<ParseTokenResp>> typeReference = new TypeReference<IMRespResult<ParseTokenResp>>() {
        };
        return JSONUtil.toBean(data, typeReference, false);
    }

    /**
     * 强制退出登录
     *
     * @param token 凭据
     * @param req   请求
     * @return 响应
     */
    public IMRespResult<String> forceLogout(IMCertificate token, ForceLogoutReq req) {
        String param = JSONUtil.toJsonStr(req);
        Request request = IMApiFactory.buildCertifiedRequest(token, param, "/auth/force_logout");
        String data = IMApiFactory.callRequest(request);
        TypeReference<IMRespResult<String>> typeReference = new TypeReference<IMRespResult<String>>() {
        };
        return JSONUtil.toBean(data, typeReference, false);
    }
}
